package com.zx.ymy.net

import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.zx.yixun.net.RxExceptionUtil
import com.zx.ymy.base.BaseActivity
import com.zx.ymy.base.BaseResponse
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

abstract class NetObserver<T>(val context: Context? = null, private val onSuccess: ((res: T?) -> Unit)? = null, private val onFailure: ((errorMsg: String?) -> Unit)? = null) : Observer<BaseResponse<T>> {

    override fun onSubscribe(d: Disposable) {
        if (!d.isDisposed) {
            if (context != null) {
                if (context is BaseActivity) {
                    context.showProgress()
                }
            }
        }
    }

    override fun onNext(res: BaseResponse<T>) {
        if (res.code == 200) {
            onSuccess?.invoke(res.data)
        } else {
            Log.e("NetObserver", "the res code= ${res.code},msg=${res.msg}")
            onFailure?.invoke(res.msg)
            onFailure(ResponseException(res),res.code.toInt(),res.msg)
        }
    }

    override fun onError(e: Throwable) {
        Log.e("NetObserver", "onError=$e")
        val errorMsg = RxExceptionUtil.exceptionHandler(e,"")
        onFailure?.invoke(errorMsg)
        onFailure(e,-1,errorMsg)
    }

    protected open fun onFailure(e: Throwable, code: Int?, errorMsg:String?) {
        if (context != null) {
            if (context is BaseActivity) {
                context.hidProgress()
            }
        }
    }


    override fun onComplete() {
        if (context != null) {
            if (context is BaseActivity) {
                context.hidProgress()
            }
        }
    }
}









